package com.oocl.servlet.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oocl.pojo.Merchant;
import com.oocl.service.MerchantManager;
import com.oocl.service.factory.MerchantManagerFactory;

@WebServlet("/login.action")
public class LoginServletAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MerchantManager merchantManager=null;
	private Merchant merchant = null;
    public LoginServletAction() {
        super();
        merchantManager = MerchantManagerFactory.getInstance();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		String errorMsg = "";
		String mName = request.getParameter("mName");
		String pwd = request.getParameter("mPwd");
		errorMsg = checkLogin(mName, pwd);
		if (errorMsg.equals("")) {
			session.setAttribute("merchant", merchant);
			response.sendRedirect("sec/home");
		}else {
			session.setAttribute("merchant", null);
			request.setAttribute("errorMsg", errorMsg);
			request.setAttribute("mName", mName);
			request.setAttribute("pwd", pwd);
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

	private String checkLogin(String mName,String pwd){
		String result="";
		if (mName.equals("")) {
			result = "账号不能为空";
			return result;
		}
		if (pwd.equals("")) {
			result = "密码不能为空";
			return result;
		}
		merchant = merchantManager.findOneMerchant(mName);
		if (merchant==null) {
			result = "账号不存在";
			return result;
		}
		if (!merchant.getmPwd().equals(pwd)) {
			result = "密码不正确";
			return result;
		}
		
		return result;
	}
	
}
